<template>
  <a-card :bordered='false' v-show='isAchClassAchievementExamScoreListCompShow'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>
          <a-col :xl='3' :lg='7' :md='8' :sm='24'>
            <a-form-model-item label='年级' prop='queryParam.gradeId'>
              <!--              v-model="queryParam.gradeId"  对应java的Controller的接收参数vo对象的属性gradeId的值 -->
              <j-dict-select-tag @change='changeGradeId' v-model='queryParam.gradeId' placeholder='请选择年级'
                                 dictCode='cou_grade,grade_name,id,tenant_id  is not null order by  grade_order' />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="6">选中值：{{ formData.gradeId}}</a-col>-->
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="考试" prop="queryParam.examinationId">
              <j-dict-select-tag  v-model="queryParam.examinationId"  placeholder="请选择考试" :dictCode="queryParamSelect.examinationIdSelect"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl='4' :lg='7' :md='8' :sm='24'>
            <a-form-model-item label='计分范围(状态)' prop='queryParam.achievementStatus'>
              <j-multi-select-tag
                v-model='queryParam.achievementStatus'
                dictCode='achievement_status'
                placeholder='请选择'>
              </j-multi-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl='4' :lg='7' :md='8' :sm='24'>
            <a-form-model-item label='评分标准' prop='queryParam.achiStandPurposeType'>
              <!--                <j-dict-select-tag @change='changeAchievementStandardId' v-model="queryParam.achievementStandardId"  :dictCode="queryParamSelect.achievementStandardIdSelect"/>-->
              <j-multi-select-tag
                v-model='queryParam.achiStandPurposeType'
                dictCode='achi_stand_purpose_type'
                placeholder='请选择'>
              </j-multi-select-tag>
            </a-form-model-item>
          </a-col>

          <a-col :xl='4' :lg='7' :md='8' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button type='primary' icon='download' @click="handleExportXls('ach_achievement_exam')">导出</a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='batchDel'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
      <template>
        <span style="float:right;">
          <a @click="searchQuery()"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <a-button v-print="'#datatable'" ghost type="primary">打印</a-button>
        </span>
      </template>
    </div>

    <!-- table区域-begin -->
    <div>
      <!--    //动态列 script 3 //////////////////////////////////////////////////////////////////////////////////////////////////////////-->
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>

        <span style='float:right;'>
          <a @click='loadDataTrRow2Col()'><a-icon type='sync' />刷新</a>
          <a-divider type='vertical' />
          <a-popover title='自定义列' trigger='click' placement='leftBottom'>
            <template slot='content'>
              <a-checkbox-group @change='onColSettingsChange' v-model='settingColumns' :defaultValue='settingColumns'>
                <a-row style='width: 400px'>
                  <template v-for='(item,index) in defColumns'>
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                        <a-col :span='12'><a-checkbox :value='item.dataIndex'><j-ellipsis :value='item.title'
                                                                                          :length='10'></j-ellipsis></a-checkbox></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a><a-icon type='setting' />设置</a>
          </a-popover>
        </span>
      </div>
      <!--    //动态列 script 3 //////////////////////////////////////////////////////////////////////////////////////////////////////////-->
      <div>
        <a-table
          ref='table'
          size='middle'
          :scroll='{x:true}'
          bordered
          rowKey='id'
          :columns='columns'
          :dataSource='dataSource'
          :pagination='ipagination'
          :loading='loading'
          :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
          class='j-table-force-nowrap'
          @change='loadDataTrRow2Col'>

        </a-table>
      </div>
    </div>

  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import AchClassAchievementExamScoreModal from './modules/AchClassAchievementExamScoreModal'
import Vue from 'vue'
import { filterObj, cloneObject, deepClone } from '@/utils/util'
import { getAction } from '@api/manage'
import { YEAR_SEMESTER } from '@/store/mutation-types'


export default {
  name: 'AchClassAchievementExamScoreListComp',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    AchClassAchievementExamScoreModal
  },
  props: {
    isAchClassAchievementExamScoreListCompShow: false,
    classIdNew: {
      type: String,
      default: ''
    },
    gradeCode: {
      type: String,
      default: ''
    },
  },
  watch: {
    classIdNew: {
      immediate: true,
      handler() {
        if(this.classIdNew){
          this.queryParam.classId = this.classIdNew
          this.searchQuery()
        }
      }
    },
    gradeCode: {
      immediate: true,
      handler() {
        if(this.gradeCode){
          this.queryParam.gradeId = this.gradeCode
          this.isDisabled = true;
          this.changeGradeId();
          this.searchQuery()
        }
      }
    }
  },
  data() {
    return {
      isDisabled: false,
      description: 'ach_achievement_exam管理页面',
      disableMixinCreated : true, //默认初始状态不加载数据

      queryParam: {
        achievementStatus: '1',    //考试状态(计分范围：1正常 2缺考 来自字典码 )
        achiStandPurposeType: '1'  //评分标准用途类型：1优良标准 2分档标准 （来自字典码）
        // subjectId: '-1',  //设置默认值：科目 -1代表总分
        //学期学年id
        // schoolYearId: this.$ls.get(YEAR_SEMESTER).schoolYearId,
        // semesterId: this.$ls.get(YEAR_SEMESTER).semesterId
      },
      //查询条件联动部分定义
      queryParamSelect: {
        examinationIdSelect: 'ach_examination,examination_name,id,del_flag  =0 and iz_open  =1  order by school_year_id desc !! semester_id !! grade_id !! create_time  desc',
      },
      //动态列 script 2 ////////////////////////////////////////////////////////////////////////////////////////////////
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      defColumns: [],
      //列定义 defColumns
      gudingColumns: [
        {
          title: '年级',
          align: 'center',
          dataIndex: 'gradeName'
        },
        {
          title: '班级',
          align: 'center',
          dataIndex: 'className'
        },
        {
          title: '班级简称',
          align: 'center',
          dataIndex: 'classNickname'
        },
        {
          title: '班级总人数',
          align: 'center',
          dataIndex: 'classStudentAllCount'
        },
        {
          title: '考试',
          align: 'center',
          dataIndex: 'examinationName'
        },
        {
          title: '参考人数',
          align: 'center',
          dataIndex: 'classStudentExamCount'
        },
        {
          title: '班级平均分',
          align: 'center',
          dataIndex: 'avgClassAchievementScore'
        },
        {
          title: '平均值排名',
          align: 'center',
          dataIndex: 'rankAvgClass'
        },
        {
          // title:() => {
          //   return (
          //     <div>
          //       <p>标准差</p>
          //       <p>(越大越波动)</p>
          //     </div>
          //   )
          // },
          title: '标准差(越大越波动)',
          align: 'center',
          dataIndex: 'stddevClassAchievementScore'
        },
        {
          title: '标准差排名',
          align: 'center',
          dataIndex: 'rankStddevClass'
        },
        {
          title: '最高分',
          align: 'center',
          dataIndex: 'maxClassAchievementScore'
        },
        {
          title: '最低分',
          align: 'center',
          dataIndex: 'minClassAchievementScore'
        },
        {
          title: '考试描述',
          align: 'center',
          dataIndex: 'classExamDescribe'
        }


      ],
      dongtaiColumns: [

        {
          title: '段位',
          align: 'center',
          dataIndex: 'standItemAliasname',//列名所在字段
          dataIndexId: 'standItemId',     //绑定数据字段(用于区分唯一列名的id，一般是列名对应的id值）
          nulldatacolname: '其他',        //空值默认值设置（如果列名为空的时候，设置为其他）
          valueIndex: 'analysisYlrs',      //数据值取值字段（对应动态列中显示的数据）
          valueIndexsuffix: '人',         //数据值的后缀单位或符号
          subColumns: [
            //预留动态列多列分组展示，暂未实现，后期优化
            {
              title: '班级优良人数',
              align: 'center',
              dataIndex: 'analysisYlrs'
            },
            {
              title: '班级优良率',
              align: 'center',
              dataIndex: 'analysisYlv'
            },
            {
              title: '优良率排名',
              align: 'center',
              dataIndex: 'rankYlvClass'
            }

          ]
        }

      ],
      //动态列 script 2 ////////////////////////////////////////////////////////////////////////////////////////////////
      url: {
        list: '/analysisachievement/achclasses/achClassAchievementExamScore/list',
        delete: '/analysisachievement/achclasses/achClassAchievementExamScore/delete',
        deleteBatch: '/analysisachievement/achclasses/achClassAchievementExamScore/deleteBatch',
        exportXlsUrl: '/analysisachievement/achclasses/achClassAchievementExamScore/exportXls',
        importExcelUrl: 'analysisachievement/achclasses/achClassAchievementExamScore/importExcel'

      },
      dictOptions: {},
      superFieldList: [],
      classId: '',
      disableMixinCreated: true,
    }
  },
  created() {
    this.initColumns();
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.$bus.$on('isAchClassAchievementExamScoreListCompShow', (val) => {
      console.log('拿到了老師關聯的班級信息')
      console.log(val)
      this.queryParam.classId = val.returnClassId
      this.searchQuery()
    })
  },
  methods: {
    initDictConfig() {
    },
    //设置查询条件的初始值
    initGradeId() {

    },
    //更改年级-->选择考试，选择班级
    changeGradeId(){
      if( this.queryParam.gradeId   ){ //判断不为空
        this.queryParamSelect.examinationIdSelect = "ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 and grade_id=\'"+ this.queryParam.gradeId + "\' and school_year_id =\'"+this.queryParam.schoolYearId+"\' and semester_id =\'"+this.queryParam.semesterId+"\'   order by school_year_id desc !! semester_id !! grade_id !! create_time  desc" ;
      }
    },
    getSuperFieldList() {
      let fieldList = []
      this.superFieldList = fieldList
    },

    //动态列 script 1 ////////////////////////////////////////////////////////////////////////////////////////
    // 列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },


    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      this.settingColumns = []

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    loadDataTrRow2ColInitColumns(testdata) {
      this.defColumns = [] //置空设置，防止重复设置
      this.columns = [] //置空设置，防止重复设置
      if (testdata == undefined || testdata == null) {
        var params = this.getQueryParams()//查询条件
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            testdata = res.result.records
            // this.loadDataTrRow2ColUtil3(testdata);
            this.loadDataTrRow2ColInitColumns(testdata)
          }
        })
      }
      //第一次遍历，制做 表头
      var th = []
      // th = this.gudingColumns; //表头 [{}] //浅拷贝
      //th = util.deepCopy(this.gudingColumns); //表头 [{}] //深拷贝
      // th = JSON.parse(JSON.stringify(this.gudingColumns)) //表头 [{}] //深拷贝1:该方法不能解决属性为函数，undefined，循环引用的的情况
      // th = cloneObject(this.gudingColumns) //深拷贝1

      // Object.assign([],th,this.gudingColumns) //表头 [{}] //深拷贝2:Object.assign 方法只会拷贝源对象自身的并且可枚举的属性到目标对象，继承属性和不可枚举属性是不能拷贝的。
      //针对深拷贝，需要使用其他办法，因为 Object.assign()拷贝的是属性值。假如源对象的属性值是一个对象的引用，那么它也只指向那个引用。
      //目前IE浏览器不兼容Object.assign()
      th = deepClone(this.gudingColumns)//表头 [{}] //深拷贝3:自定义递归函数解决深拷贝问题

      var thKeyCol = {} //动态关键列,需重新定义，动态获取


      //筛选科目分项
      var thKey = {}
      for (var i = 0; i < testdata.length; i++) {
        var d = testdata[i]
        var dontaicolName = this.dongtaiColumns[0].dataIndex
        var dontaicolId = this.dongtaiColumns[0].dataIndexId
        if (d[dontaicolName] != undefined && d[dontaicolName] != null && d[dontaicolName] != 'null' && d[dontaicolName] != '') {
          // thKey[d[dontaicolName] ] =1 ;
          thKey[d[dontaicolName]] = d[dontaicolId]  //动态列

          // thKey[eval("d."+dontaicolId)] =2;
        } else if (d[dontaicolName] == null || d[dontaicolName] != 'null' || d[dontaicolName] != '') {
          thKey[this.dongtaiColumns[0].nulldatacolname] = this.dongtaiColumns[0].nulldatacolname  //动态列

        } else {
          thKey['-1'] = '-1'
        }

        // if(  d[dontaicolId] != undefined && d[dontaicolId] != null && d[dontaicolId] != 'null' && d[dontaicolId] != '' ){
        //   thKey[d[dontaicolId] ] = 2;  //动态列
        // }

      }

      //把科目加到th里面 ，动态增长列
      // for (var key in Object.keys(thKey))
      for (var key in thKey) {
        var colobj = { title: key, align: 'center', dataIndex: thKey[key] }
        th.push(colobj)
        thKeyCol[key] = key
      }
      // this.tableHeader = th;
      //重新定义列，增加动态列
      // if (this.defColumns == undefined || this.defColumns == null || this.defColumns.length ==0 ){
      //   this.defColumns = th;
      //   // this.initColumns();
      // }
      // if (this.columns == undefined || this.columns == null || this.columns.length ==0){
      //   this.columns = th;
      // }
      this.defColumns = th
      this.columns = th
      this.initColumns()
    },
    loadDataTrRow2ColInitDatas(testdata) {
      //第二次遍历，制做tr的行
      var tr = [] //数据 [{}]

      for (var i = 0; i < testdata.length; i++) {
        var d = testdata[i]
        var rowdata = {}
        for (var j = 0; j < this.gudingColumns.length; j++) {
          rowdata[this.gudingColumns[j].dataIndex] = d[this.gudingColumns[j].dataIndex] //用对应列的数据赋值给固定列
        }


        //判断对象是否存在，存在则忽略，不存在则插入
        if (tr.length == 0) {
          tr.push(rowdata)
        } else {
          var insertflag = true
          for (var k in tr) {
            var eqflag = true
            for (var rd in rowdata) {
              if (rowdata[rd] !== tr[k][rd]) {
                eqflag = false
                continue
              }
            }
            //判断是否相等
            // if (Object.is(rowdata,tr[k])){
            // if ( this.compare(rowdata,tr[k]) ){
            if (eqflag) {
              insertflag = false
            } else {
              continue
            }
          }
          //应当插入则插入：即不存在则插入
          if (insertflag) {
            tr.push(rowdata)
          }
        }

      }
      //第三次遍历，添加科目的成绩:动态插入数据列
      for (var i = 0; i < testdata.length; i++) {
        var d = testdata[i]
        //查找应该是tr的第几条数据
        var trindex = -1
        for (var ti = 0; ti < tr.length; ti++) {
          var tr_rowdata = tr[ti]//取出1条数据
          var equalflag = true
          for (var j = 0; j < this.gudingColumns.length; j++) {
            if (tr_rowdata[this.gudingColumns[j].dataIndex] != d[this.gudingColumns[j].dataIndex]) { //用对应列的数据赋值给固定列
              equalflag = false
            }
          }
          //如果相等即找到了,则写入数据,考虑动态列寻找
          if (equalflag) {
            //直接赋值：给对应动态列的值设置为成绩数值（会存在空值串列的情况，需考虑空值设置问题）
            //考虑到数据是通过列名绑定，就不会存在串列问题
            if (d[this.dongtaiColumns[0].dataIndexId] != undefined && d[this.dongtaiColumns[0].dataIndexId] != null && d[this.dongtaiColumns[0].dataIndexId] != '') {
              tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumns[0].valueIndex] + this.dongtaiColumns[0].valueIndexsuffix //把成绩数据绑定到动态列名上,加后缀单位
            } else {
              tr_rowdata[this.dongtaiColumns[0].nulldatacolname] = d[this.dongtaiColumns[0].valueIndex] + this.dongtaiColumns[0].valueIndexsuffix //把成绩数据绑定到动态列名上,加后缀单位
            }


            //通过循环判断，确定应该给哪个动态列赋值（避免空值串列问题）
            // for (var key in thKeyCol ){
            //   if (d[this.dongtaiColumns[0].dataIndex] == key ) {
            //     tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumnsValue[0].dataIndex] ;  //动态列的成绩数值
            //   }
            //   else if (tr_rowdata[key] == undefined || tr_rowdata[key] ==null || tr_rowdata[key] == ''){
            //     //补充其他学科为空值
            //     tr_rowdata[key] = null;
            //   }
            //   else if(tr_rowdata[key] != null){
            //     continue;//已经有值了，无需处理
            //   }
            //   else{
            //     //补充其他学科为-1异常情况
            //     tr_rowdata[key] = -1;
            //   }
            // }
          }
          tr[ti] = tr_rowdata //重新定义一行数据，把动态列数据加入进来
        }

      }

      this.dataSource = tr  //重新定义数据：用分组动态列进行行列转换后的新数据

    },
    async loadDataTrRow2Col() {
      //获得测试数据
      // var testdata = this.dataSource ;
      var testdata = []
      this.defColumns = []
      this.columns = []
      this.settingColumns = []

      var params = this.getQueryParams()//查询条件
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          testdata = res.result.records
          // this.loadDataTrRow2ColUtil3(testdata);
          this.loadDataTrRow2ColInitColumns(testdata) //列名已经初始化了，只需初始化1次，不必重复初始化
          this.loadDataTrRow2ColInitDatas(testdata)  //更新数据样式格式

        }
      })
    },
    searchQuery() {
      this.dataSource = []
      if (this.queryParam.classId) {
        this.loadDataTrRow2Col(1)
        // 点击查询清空列表选中行
        // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
        this.selectedRowKeys = []
        this.selectionRows = []
      }
    },
    searchReset() {
      this.queryParam = {}
      this.loadDataTrRow2Col(1)
    },
    //
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadDataTrRow2Col()
    }
    //动态列 script 1 ////////////////////////////////////////////////////////////////////////////////////////
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>